package com.ztesoft.huangfu.learning.springboot.springbootvalidate.controller;

import com.ztesoft.huangfu.learning.springboot.springbootvalidate.entity.Book;
import com.ztesoft.huangfu.learning.springboot.springbootvalidate.annotation.DateTime;
import com.ztesoft.huangfu.learning.springboot.springbootvalidate.entity.User;
import com.ztesoft.huangfu.learning.springboot.springbootvalidate.groups.Groups;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

/**
 * Created with IntelliJ IDEA.
 * Author: huangfu.daohui
 * Date: 2018/6/8
 * Time: 21:22
 * Version: 1.0
 * Description: 校验字符串和实体
 * http://blog.battcn.com/2018/06/01/springboot/v2-other-exception/
 **/
// @Validated注解一定要加上
@Validated
@RestController
public class ValidateController {
    //字符串验证
    @GetMapping("/validateString")
    public String validateString(@NotBlank(message = "name 不能为空") @Length(min = 2, max = 10, message = "name 长度必须在 {min} - {max} 之间") String name) {
        return "success";
    }

    // 实体验证
    @GetMapping("/validateEntity")
    public String validateEntity(@Validated Book book) {
        return "success";
    }

    // 自定义注解验证
    @GetMapping("/validateAnnotation")
    public String validateAnnotation(@NotBlank(message = "date 不能为空") @DateTime(message = "您输入的格式错误，正确的格式为：{format}", format = "yyyy-MM-dd HH:mm") String date) {
        return "success";
    }

    /**
     * 分组验证group
     * id，新增可为空，修改不为空
     */
    // 只要验证实体中Groups.Default分组的字段
    @PostMapping("/insert")
    public String insert(@Validated(value = Groups.Default.class) User user) {
        return "sucess";
    }
    // 实体中 groups中Default Update的字段都要验证
    @GetMapping("/update")
    public String update(@Validated(value = {Groups.Default.class, Groups.Update.class}) User user) {
        return "success";
    }
}
